<template>
  <n-modal v-model:show="showModal" preset="dialog" :show-icon="false">
    <n-card v-if="editType==='add' || editType==='edit'">
      <div class="text-center my-2 text-3xl">{{title}}</div>
      <flexform  ref="flexFormref" :formList="formList" :formValue="formValue">
      </flexform>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">取消</n-button>
          <n-button @click="handleOK" type="primary">确定</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='view'">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <descriptions :infoList="_lanmulist"></descriptions>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="clickEdit" type="primary">编辑</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='success'">
      <n-result status="success" title="成功" :description="formValue.id?'编辑成功':'创建成功'">
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='error'">
      <n-result status="error" title="错误">
        <template>
          <p>{{ errortext }}</p>
        </template>
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="getreturn" type="primary">返回</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup name="studyEdit">
import {useRoute, useRouter} from "vue-router";
import http from "@/request/request"
import {isObject} from "../../../../util/isObject";
import guiling from "../../../../util/guiling";
const router = useRouter()
const route = useRoute()
const flexFormref = ref(null)
const showModal = ref(false)
const typeflag = ref("add")
const title = ref("")
const formValue = ref({})
const formData = ref({})
const init = (type, item = null) => {
  if(item){
    formData.value = {...item}
    Object.keys(formData.value).forEach(el=>{
      if(isObject(formData.value[el])){
        formValue.value[el] = formData.value[el].id
      }else{
        formValue.value[el] = formData.value[el]
      }
    })
    // 特殊处理部分
    formValue.value["rangetime"] = [parseInt(formData.value["startTime"]),parseInt(formData.value["endTime"])]
    formValue.value["complete"] = formValue.value["complete"].toString()
  }
  // 初始化的时候，获取备选字段
  getalldict()
  showModal.value = true
  editType.value = type
  switch (editType.value) {
    case "add":
      title.value = "新建"
      break;
    case "view":
      title.value = "详情"
      break;
    case "edit":
      title.value = "编辑"
      break;
  }
}
const emit = defineEmits(["shuaxin"])
const doClose = () => {
  showModal.value = false
  emit("shuaxin")
}
const reset = () => {
  console.log("重置数据")
  title.value = "新建"
  typeflag.value = "add"
  formValue.value = guiling(formValue.value)
  formData.value = {}
}
// 点击确定
const handleOK = () => {
  flexFormref.value.jiaoyan((value) => {
    value.endTime = value.rangetime[1]
    value.startTime = value.rangetime[0]
    if(formValue.value.id){
      http.putstudyinfo(value,formValue.value.id).then(res => {
        if (res.data.code === 0) {
          getsuccess()
        }else{
          getfaild(res.data.error)
        }
      }).catch(error=>{
        getfaild(error)
      })
    }else{
      http.addstudyinfo(value).then(res => {
        if (res.data.code === 0) {
          getsuccess()
        }else{
          getfaild(res.data.error)
        }
      }).catch(error=>{
        getfaild(error)
      })
    }
  })
}

// 交互成功
const getsuccess = () => {
  editType.value = "success"
  setTimeout(() => {
    doClose()
  }, 500)
}
const editType= ref("")
// 交互失败
const getfaild = (jieguo) => {
  editType.value = "error"
  errortext.value = jieguo.toString()
}

// 点击返回
const getreturn = () => {
  if (formValue.value.id) {
    editType.value = "edit"
    title.value = "编辑"
  } else {
    editType.value = "add"
    title.value = "创建"
  }
  errortext.value = ""
}
// 表单配置
const formList = ref([
  {label: "学校名称", key: "schoolname", type: "input",placeholder:"请输入学校名称",rules:[{required:true,message:"请输入学校名称",},{max:200,min:2,message:"长度2-200"}]},
  {label: "专业", key: "zhuanye", type: "input",placeholder:"请输入专业",rules:[{required:true,message:"请输入专业"},{max:200,min:2,message:"长度2-200"}]},
  {label: "学校地址", key: "schoolarea", type: "input",placeholder:"请输入学校地址",rules:[{required:true,message:"请输入学校地址"},{max:200,min:2,message:"长度2-200"}]},
  {label:"学制",key:"xuezhi" ,type: "select",selectkey:"xuezhi",placeholder:"请选择学制",options:[],rules:[{required:true,message:"请选择学制"},],},
  {label:"是否结业",key:"complete" ,type: "select",placeholder:"请选择是否结业",options:[{label:"是",value:"1"},{label:"否",value:"2"},],rules:[{required:true,message:"请选择是否结业"},],},
  {label:"学历",key:"level" ,type: "select",placeholder:"请选择学历",selectkey:"xueli",options:[],rules:[{required:true,message:"请选择学历"},],},
  {label:"时间",key:"rangetime" ,type: "picker",datetype:"daterange",placeholder:"请选择时间",rules:[{required:true,message:"请选择时间"},],},
])

// 向后台获取自定义的字典
const getdict=(formitem)=>{
  // 如果这个字段已经获取了，就不再获取
  if(formitem.options && formitem.options.length > 0){
    return
  }
  const params = {
    value:formitem.selectkey
  }
  http.zidianfilter(params).then(res=>{
    if(res.data.code===0){
      formitem.options = res.data.items.map(item=>{
        return {label:item.name,value:item.id}
      })
    }
  })
}

// 把表单配置里面的自定义字段从后台获取
const getalldict=()=>{
  for (let i=0;i<formList.value.length;i++){
    if(formList.value[i].selectkey){
      getdict(formList.value[i])
    }
  }
}

// 显示相关的配置
const lanmulist = ref([
  {label: "学校名称", key: "schoolname"},
  {label: "学校地址", key: "schoolarea"},
  {
    label: "学历", key: "level", render: (data) => {
      return data ? data.name :""
    }
  },
  {
    label: "学制", key: "xuezhi",  render: (data) => {
      return data ? data.name :""
    }
  },
  {label: "专业名称", key: "zhuanye", },
  {
    label: "是否毕业", key: "complete",  render: (data) => {
      return data === 1 ? "毕业" : "肄业"
    }
  },
  {
    label: "开始时间", key: "startTime",  render: (data) => {
      return data ? new Date(parseInt(data)).toLocaleString("zh", {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
      }):""
    }
  },
  {
    label: "结束时间", key: "endTime",  render: (data) => {
      return data ? new Date(parseInt(data)).toLocaleString("zh", {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
      }):""
    }
  },
  {label: "创建时间", key: "createdTime",render: (data)=>{
      return data ? new Date(parseInt(data)).toLocaleString("zh", {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour12: false,
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      }) :""
    }},
])
const _lanmulist = computed(() => {
  return lanmulist.value.map(item => {
    return {...item, value: item.render?item.render(formData.value[item.key]) : formData.value[item.key]}
  })
})

// 点击编辑按钮
const clickEdit = () => {
  editType.value = "edit"
  title.value = "编辑"
}
// 抛出属性和方法
defineExpose({init, doClose, reset})
// 初始化区域
</script>

<style scoped>

</style>
